package cn.learn.server.persistence;

import cn.learn.server.DataTree;
import cn.learn.server.Request;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class FileTxnSnapLog {
    final File dataDir;
    final File snapDir;

    FileSnap snapLog;
    public static final int VERSION = 2;
    public static final String version = "version-";

    public static final String ZOOKEEPER_DATADIR_AUTOCREATE = "zookeeper.datadir.autocreate";

    public static final String ZOOKEEPER_DATADIR_AUTOCREATE_DEFAULT = "true";

    public FileTxnSnapLog(File dataDir, File snapDir) {
        this.dataDir = new File(dataDir, version + VERSION);
        this.snapDir = new File(snapDir, version + VERSION);

        boolean enableAutocreate = Boolean.parseBoolean(
                System.getProperty(ZOOKEEPER_DATADIR_AUTOCREATE, ZOOKEEPER_DATADIR_AUTOCREATE_DEFAULT));

        if (!this.snapDir.exists()) {
            if (!enableAutocreate) {

            }
            if (!this.snapDir.mkdirs() && !this.snapDir.exists()) {

            }
        }
        snapLog = new FileSnap(this.snapDir);
    }

    public void save(DataTree dataTree,
                     ConcurrentHashMap<Long, Integer> sessionsWithTimeouts,
                     boolean syncSnap) throws IOException {
        long lastZxid = dataTree.lastProcessedZxid;
        File snapshotFile = new File(snapDir, Util.makeSnapshotName(lastZxid));
        System.out.println(snapshotFile.getAbsolutePath());
        snapLog.serialize(dataTree, sessionsWithTimeouts, snapshotFile, syncSnap);
    }

    public long restore(DataTree dt, Map<Long, Integer> sessions) throws IOException {
        long deserializeResult = snapLog.deserialize(dt, sessions);
        return deserializeResult;
    }

    public boolean append(Request si) {
//        return txnLog.append(si.getHdr(), si.getTxn(), si.getTxnDigest());
        return true;
    }
}
